#!/usr/local/bin/python
import os
import sys
import fnmatch
from time import sleep

## Initial stuff
_scriptName = os.path.basename(__file__)
_scriptPath = sys.argv[0]
_scriptWDir = _scriptPath.replace(_scriptName,"")
_scriptVers = "0.1"
_configFile = _scriptWDir + _scriptName.replace(".py",".config")

## Global config info
config = {"source":None,"recurs":False,"target":None}
softErrors = []
fatalError = None
pidFile = "/opt/isoserver/.pid"

def chkSystem():
	os.system('MAKEDEV loop')
	'''
	numberOfLoopDevices = 10
	for d in range(numberOfLoopDevices):
		os.system('MAKEDEV -v /dev/iso-server'+str(d))
	'''

def chkStop():
	if len(sys.argv) >= 2:
		if sys.argv[1].upper()== "STOP":
			return(True)

def chkSilent():
	if len(sys.argv) >= 2:
		if sys.argv[1].upper()== "SILENT":
			return(True)

def chkErr(method=None):
	if method == None:
		print("Errors:")
		for e in softErrors:
			print(e)
	try:
		if method[0].upper() == "FATALERROR":
			print("Fatal Error!")
			print(method[1])
			sys.exit(1)
		if method[0].upper() == "ERROR":
			softErrors.append(method[1])
	except:
		return(method)

def loadConfig(file=_configFile):
	try:
		cfg = open(file,'r')
		cfgArr = []
		for l in cfg:
			l = l.replace("\n","")
			if l != "":
				cfgArr.append(l.split("#",1)[0])
		cfg.close()
		for c in cfgArr:
			cfgOptions = ["source","recurs","target","mkdirt","srfreq"]
			for o in cfgOptions:
				if c.split("=")[0] == o:
					if c.split("=")[1].upper() == "TRUE":
						config[o] = True
					elif c.split("=")[1].upper() == "FALSE":
						config[o] = False
					else:
						config[o] = c.split("=")[1]
		config["source"] = config["source"].replace("\r","").split(",")
		config["target"] = config["target"].replace("\r","").split(",")
		return(config)
	except:
		return(["FatalError","Could not load config file!"])

def createFolders():
	if config["mkdirt"]:
		for d in config["target"]:
			if not os.path.exists(d):
				print "Creating: " + d
				os.makedirs(d)
				
def getISOs():
	isoFiles = []
	duplicates = []
	fileExtensions = ["iso","ISO","Iso"]
	for d in config["source"]:
		for root, dirnames, filenames in os.walk(d):
			for e in fileExtensions:
				for filename in fnmatch.filter(filenames, '*.' + e):
					isoFiles.append(os.path.join(root, filename))
	for a in isoFiles:
		for b in isoFiles:
			if a == b:
				duplicates.append(a)
	isoFiles.sort()
	#for i in duplicates:print i
	return(list(set(isoFiles)))

def createMountDirs(isos,create=True):
	targetDirs = []
	for i in isos:
		dirname = os.path.splitext(os.path.basename(i))[0]
		for t in config["target"]:
			targetDirs.append(t + "/" + dirname)
	if create:
		for d in targetDirs:
			if not os.path.isdir(d):
				os.makedirs(d)
	return(targetDirs)

def unmount(dirs):
	for d in dirs:
		for t in os.listdir(d):
			command = 'umount "'+d+"/"+t+'"'
			#print command
			os.system(command)

def removeEmptyDirs(dirs):
	for d in dirs:
		for t in os.listdir(d):
			targetDir = d+"/"+t
			if not os.listdir(targetDir):
				os.rmdir(targetDir)

def panel(dirs):
	if chkStop():
		print("ISO-Server Stopped")
	else: 
		if not chkSilent():
			os.system("clear")
			print("\n\t\tISO-Server\n\n\tLooking for ISOs in:\n\t---------------------------")
			for i in config["source"]:
				print("\t" + i)
			print("\n\n\tMounting in the folder(s):\n\t---------------------------")
			for i in config["target"]:
				print("\t" + i)
			print("\n\n\tFiles Mounted as:\n\t---------------------------")
			for d in dirs:
				for t in os.listdir(d):
					targetDir = "\t"+d+"/"+t
					print(targetDir)
			print("\n\t\tWaiting " + config["srfreq"] + " seconds until next cycle.")

def mount(files):
	mounts = []
	commands = []
	for i in files:
		destFolders = []
		isoName = os.path.basename(i)
		folderName = os.path.splitext(isoName)[0]
		for f in config["target"]:
			destFolders.append(f+"/"+folderName)
		mounts.append([i,destFolders])
	for m in mounts:
		for d in m[1]:
			commands.append('mount -t udf,iso13346 -o loop "'+m[0]+'" "'+d+'/" > /dev/null 2>&1')
			commands.append('mount -t iso9660 -o loop "'+m[0]+'" "'+d+'/" > /dev/null 2>&1')
	for c in commands:
		os.system(c)

running = True
while running:
	chkSystem()
	chkErr(loadConfig())
	createFolders()
	isoFiles = getISOs()
	unmount(config["target"])
	try:createMountDirs(isoFiles)
	except:pass
	if not chkStop(): mount(isoFiles)
	removeEmptyDirs(config["target"])
	panel(config["target"])
	if chkStop():
		running = False
	else:
		sleep(int(config["srfreq"]))
killCommand = 'kill `cat '+pidFile+'`'
os.system(killCommand)